//
//  StringExtension.swift
//  zhende
//
//  Created by chenliang on 2016/12/24.
//  Copyright © 2016年 chenliang. All rights reserved.
//

import Foundation

extension String {
    
    func qrCode() -> UIImage {
        let data = self.data(using: String.Encoding.utf8)
        //系统自带的
        //        CIAztecCodeGenerator
        //        CICode128BarcodeGenerator
        //        CIPDF417BarcodeGenerator
        //        CIQRCodeGenerator
        //实例化二维码滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        //        //恢复滤镜的默认属性
        //        filter?.setDefaults()
        //通过KVO设置滤镜inputMessage数据
        filter?.setValue(data, forKey: "inputMessage")
        filter?.setValue("H", forKey: "inputCorrectionLevel")
        
        //上色（设置二维码的底色和码色，input0是码色，input1是底色）
        let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage":filter!.outputImage!,"inputColor0":CIColor(cgColor: UIColor.black.cgColor),"inputColor1":CIColor(cgColor: UIColor.white.cgColor)])
        
        //获得滤镜输出的图像
        let qrCodeImage = colorFilter!.outputImage
        let scaleX = 200 / (qrCodeImage?.extent.size.width)!
        let scaleY = 200 / (qrCodeImage?.extent.size.height)!
        let transformedImage = qrCodeImage?.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
        return UIImage.init(ciImage: transformedImage!)
    }
    
    func yy_isValidateName() -> Bool {
        let b = "^[\\u4E00-\\u9FA5A-Za-z0-9_]{1}[\\u4E00-\\u9FA5A-Za-z0-9_\\s]*[\\u4E00-\\u9FA5A-Za-z0-9_]{1}$"
        let p = NSPredicate(format: "SELF MATCHES %@", b)
        return p.evaluate(with: self)
    }
    
    func yy_isValidateMoney() -> Bool {
        let b = "^\\d{0,8}\\.{0,1}(\\d{1,2})?$"
        let p = NSPredicate(format: "SELF MATCHES %@", b)
        return p.evaluate(with: self)
    }
    
    /**
     *  汉字转拼音
     *
     *  - Parameters:
     *      - needDiacritics: 是否需要读音符号，默认false
     *
     *  - Returns: 拼音字符串
     */
    func yy_chineseSpell(hasDiacritics: Bool = false) -> String {
        let mString: NSMutableString = NSMutableString(string: self)
        if CFStringTransform(mString, nil, kCFStringTransformMandarinLatin, false) {
            if hasDiacritics {
                return mString as String
            } else if CFStringTransform(mString, nil, kCFStringTransformStripDiacritics, false) {
                return mString as String
            }
        }
        return self
    }
    
    /**
     *  获得首字母
     *
     *  - Parameters:
     *      - isCapital: 是否大写
     *
     *  - Returns: 首字母
     */
    func yy_firstCharacter(isCapital: Bool = true) -> String {
        if isCapital {
            return String(yy_chineseSpell()[startIndex]).uppercased()
        }
        return String(yy_chineseSpell()[startIndex])
    }
    
}
